package com.ruoyi.safe.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quality.domain.TQualityFileItem;
import com.ruoyi.quality.mapper.TQualityFileItemMapper;
import com.ruoyi.quality.service.ITQualityFileItemService;
import com.ruoyi.safe.domain.BizProjectCheckRecord;
import com.ruoyi.safe.domain.BizRectifyReview;
import com.ruoyi.safe.domain.CommonProject;
import com.ruoyi.safe.domain.dto.ProjectSearchDTO;
import com.ruoyi.safe.domain.dto.UserSearchDTO;
import com.ruoyi.safe.domain.vo.CommonProjectVO;
import com.ruoyi.safe.domain.vo.CommonUserVO;
import com.ruoyi.safe.mapper.BizProjectCheckRecordMapper;
import com.ruoyi.safe.mapper.BizRectifyReviewMapper;
import com.ruoyi.safe.mapper.CommonProjectMapper;
import com.ruoyi.safe.mapper.CommonUserMapper;
import com.ruoyi.safe.service.ICommonProjectService;
import com.ruoyi.system.domain.vo.UserMessageVO;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 项目管理Service业务层处理
 *
 * @author buxi
 * @date 2023-11-08
 */
@Slf4j
@Service
@AllArgsConstructor
public class CommonProjectServiceImpl implements ICommonProjectService {

    private final CommonProjectMapper commonProjectMapper;

    private final SysUserMapper sysUserMapper;

    private final CommonUserMapper commonUserMapper;

    private final SysDeptMapper sysDeptMapper;

    private final BizRectifyReviewMapper bizRectifyReviewMapper;

    private final BizProjectCheckRecordMapper bizProjectCheckRecordMapper;

    private final TQualityFileItemMapper tQualityFileItemMapper;
    /**
     * 查询项目管理
     *
     * @param id 项目管理主键
     * @return 项目管理
     */
    @Override
    public CommonProject selectCommonProjectById(Long id) {
        CommonProject commonProject = commonProjectMapper.selectCommonProjectById(id);
        if (commonProject != null && StringUtils.isNotBlank(commonProject.getLicense())) {
            List<String> licenses = Arrays.stream(commonProject.getLicense().split(","))
                    .map(String::trim)
                    .collect(Collectors.toList());
            commonProject.setLicenses(licenses);
        }
        return commonProject;
    }

    /**
     * 查询项目管理列表
     *
     * @param projectSearch 项目管理
     * @return 项目管理
     */
    @Override
    public List<CommonProjectVO> selectCommonProjectList(ProjectSearchDTO projectSearch) {
        return commonProjectMapper.selectCommonProjectList(projectSearch);
    }

    @Override
    public List<CommonProject> selectCommonProjectListExcel(ProjectSearchDTO projectSearch) {
        return commonProjectMapper.selectCommonProjectListExcel(projectSearch);
    }

    /**
     * 新增项目管理
     *
     * @param commonProject 项目管理
     * @return 结果
     */
    @Override
    public int insertCommonProject(CommonProject commonProject) {
        if (commonProjectMapper.selectCommonProjectNameExist(commonProject.getName().trim()) > 0) {
            throw new ServiceException("项目名称已存在");
        }
        commonProject.setCreateTime(DateUtils.getNowDate());
        commonProject.setCreateBy(SecurityUtils.getUsername());
        calculateDateCount(commonProject);

        if (!CollectionUtils.isEmpty(commonProject.getLicenses())) {
            commonProject.setLicense(StringUtils.join(commonProject.getLicenses(), ","));
        }
        return commonProjectMapper.insertCommonProject(commonProject);
    }

    /**
     * 修改项目管理
     *
     * @param commonProject 项目管理
     * @return 结果
     */
    @Override
    public int updateCommonProject(CommonProject commonProject) {
        if (commonProjectMapper.selectCommonProjectNameExist2(commonProject.getName(), commonProject.getId()) > 0) {

            throw new ServiceException("项目名称已存在");
        }
        calculateDateCount(commonProject);
        commonProject.setUpdateTime(DateUtils.getNowDate());
        commonProject.setUpdateBy(SecurityUtils.getUsername());
        if (!CollectionUtils.isEmpty(commonProject.getLicenses())) {
            commonProject.setLicense(StringUtils.join(commonProject.getLicenses(), ","));
        }
        return commonProjectMapper.updateCommonProject(commonProject);
    }

    /**
     * 批量删除项目管理
     *
     * @param ids 需要删除的项目管理主键
     * @return 结果
     */
    @Override
    public int deleteCommonProjectByIds(Long[] ids) {
        return commonProjectMapper.deleteCommonProjectByIds(ids);
    }

    /**
     * 删除项目管理信息
     *
     * @param id 项目管理主键
     * @return 结果
     */
    @Override
    public int deleteCommonProjectById(Long id) {
        return commonProjectMapper.deleteCommonProjectById(id);
    }

    @Override
    public Set<CommonProjectVO> selInProjectList() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        return commonProjectMapper.selInProjectList(loginUser.getDeptId(), loginUser.getUserId());
    }

    @Override
    public Set<CommonProjectVO> selInProjectList(String userName) {
        SysUser sysUser = sysUserMapper.selectUserByUserName(userName);
        if (sysUser == null) {
            throw new RuntimeException("用户不存在");
        }
        Set<CommonProjectVO> commonProjectVOS = commonProjectMapper.selInProjectList(sysUser.getDeptId(), sysUser.getUserId());
        commonProjectVOS.forEach(s -> s.setProjectStatus(DictUtils.getDictLabel("common_project_status", s.getProjectStatus())));
        return commonProjectVOS;
    }

    @Override
    public List<Map<String,Object>> getSimpleObjectList(CommonProject commonProject) {
        return commonProjectMapper.selectSimpleList(commonProject);
    }

    @Override
    public List<UserMessageVO> transferUser(Long projectId) {

        UserSearchDTO userSearchDTO = new UserSearchDTO();
        userSearchDTO.setProjectId(projectId);
        List<CommonUserVO> commonUserVOS = commonUserMapper.selectCommonUserList(userSearchDTO);
        List<UserMessageVO> userMessageVOS = new ArrayList<>();
        //查询签约单位
        CommonProject commonProject = commonProjectMapper.selectCommonProjectById(projectId);
        //查询签约单位的详细信息
        SysDept sysDept = sysDeptMapper.selectDeptById(commonProject.getSigningDept());
        //查询签约单位的上级部门的人员
        List<Long> deptIds = Arrays.stream(sysDept.getAncestors().split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<Long> longs = sysUserMapper.selectUserListByDeptIds(deptIds);
        List<UserMessageVO> userMessageVOS1 = sysUserMapper.selectUserMessageVOListByUserIds(StringUtils.join(longs, ","));
        //将签约单位的部门人员和上级部门的人员进行合并
        commonUserVOS.forEach(item -> {
            UserMessageVO userMessageVO = new UserMessageVO();
            userMessageVO.setUserId(item.getUserId());
            userMessageVO.setUserName(item.getUserName());
            userMessageVO.setUserPhone(item.getPhone());
            userMessageVO.setNickName(item.getNickName());
            SecurityUtils.getUsername();
            userMessageVO.setProjectLevel("项目人员");
            userMessageVO.setDeptName(item.getDeptName());
            userMessageVOS.add(userMessageVO);
        });
        userMessageVOS1.forEach(item -> {
            UserMessageVO userMessageVO = new UserMessageVO();
            userMessageVO.setUserId(item.getUserId());
            userMessageVO.setUserName(item.getUserName());
            userMessageVO.setUserPhone(item.getUserPhone());
            userMessageVO.setNickName(item.getNickName());
            SecurityUtils.getUsername();
            userMessageVO.setProjectLevel("上级人员");
            userMessageVO.setDeptName(item.getDeptName());
            userMessageVOS.removeIf(userMessageVO1 -> userMessageVO1.getUserId().equals(item.getUserId()));
            userMessageVOS.add(userMessageVO);
        });
        //使用stream流进行去重并返回
        return userMessageVOS;
    }

    @Override
    @Transactional
    public int insertBizRectifyReview(BizRectifyReview bizRectifyReview) {

        bizRectifyReview.setId(IdUtil.getSnowflakeNextId());

        bizRectifyReview.setOperatorer(SecurityUtils.getUsername());
        bizRectifyReview.setOperatorTime(DateUtils.getNowDate());

        bizRectifyReview.setCreateBy(SecurityUtils.getUsername());
        bizRectifyReview.setCreateTime(DateUtils.getNowDate());
        bizRectifyReview.setOperatorType("3");

//        BizProjectCheckRecord bizProjectCheckRecord = new BizProjectCheckRecord();
//
//        bizProjectCheckRecord.setId(bizRectifyReview.getRecordId());
//
//        bizProjectCheckRecord.setRevisePeople(bizRectifyReview.getRemoveUserName());
//
//        bizProjectCheckRecord.setUpdateBy(SecurityUtils.getUsername());
//
//        bizProjectCheckRecord.setUpdateTime(DateUtils.getNowDate());
//        bizProjectCheckRecordMapper.updateBizProjectCheckRecord(bizProjectCheckRecord);

        TQualityFileItem item =  new TQualityFileItem();
        item.setId(bizRectifyReview.getRecordId());
        item.setRevisePeopleId(bizRectifyReview.getRemoveUserName());
        item.setUpdateBy(SecurityUtils.getUsername());
        item.setUpdateTime(DateUtils.getNowDate());
        tQualityFileItemMapper.updateTQualityFileItem(item);

        return bizRectifyReviewMapper.insertBizRectifyReview(bizRectifyReview);
    }

    @Override
    public CommonProject selectCommonProjectByGapsProjectId(String gapsProjectId) {
        return commonProjectMapper.selectCommonProjectByGapsProjectId(gapsProjectId);
    }

    @Override
    public int insertSyncCommonProject(CommonProject commonProject) {
        if (commonProjectMapper.selectCommonProjectNameExist(commonProject.getName().trim()) > 0) {
            throw new ServiceException("项目名称已存在");
        }
        calculateDateCount(commonProject);
        if (!CollectionUtils.isEmpty(commonProject.getLicenses())) {
            commonProject.setLicense(StringUtils.join(commonProject.getLicenses(), ","));
        }
        return commonProjectMapper.insertCommonProject(commonProject);
    }

    @Override
    public int updateSyncCommonProject(CommonProject commonProject) {
        if (commonProjectMapper.selectCommonProjectNameExist2(commonProject.getName(), commonProject.getId()) > 0) {
            throw new ServiceException("项目名称已存在");
        }
        calculateDateCount(commonProject);
        if (!CollectionUtils.isEmpty(commonProject.getLicenses())) {
            commonProject.setLicense(StringUtils.join(commonProject.getLicenses(), ","));
        }
        return commonProjectMapper.updateCommonProject(commonProject);
    }

    /**
     * 计算项目的天数
     */
    private void calculateDateCount(CommonProject commonProject) {


        if (StringUtils.isNotNull(commonProject.getStartDate()) && StringUtils.isNotNull(commonProject.getEndDate())) {

            if (DateUtil.compare(commonProject.getStartDate(), commonProject.getEndDate()) > 0) {
                throw new ServiceException("项目开始时间不能大于结束时间");
            }

            commonProject.setDateCount(DateUtil.betweenDay(commonProject.getStartDate(), commonProject.getEndDate(), false));
        }
        if (StringUtils.isNotNull(commonProject.getRealStartDate()) && StringUtils.isNotNull(commonProject.getRealEndDate())) {

            if (DateUtil.compare(commonProject.getRealStartDate(), commonProject.getRealEndDate()) > 0) {
                throw new ServiceException("项目实际开始时间不能大于实际结束时间");
            }

            commonProject.setRealDateCount(DateUtil.betweenDay(commonProject.getRealStartDate(), commonProject.getRealEndDate(), false));
        }
    }
}
